package com.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cens.common.utils.R;
import com.mall.cart.feign.CommodityFeignService;
import com.mall.cart.interceptor.CartInterceptor;
import com.mall.cart.service.CartService;
import com.mall.cart.vo.Cart;
import com.mall.cart.vo.CartItem;
import com.mall.cart.vo.SkuInfoVo;
import com.mall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    private static final String CART_PREFIX = "mall:cart:";
    @Autowired
    private CommodityFeignService commodityFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, String, String> ops = getCartOps();

        String res = ops.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();
            //添加新商品至购物车
            cartItem.setSkuId(skuId);
            cartItem.setCheck(true);
            cartItem.setCount(num);
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(
                    () -> {
                        //1、查询商品信息
                        R skuInfo = commodityFeignService.getSkuInfo(skuId);
                        SkuInfoVo skuInfoData = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        //2、封装购物车商品项
                        cartItem.setImage(skuInfoData.getSkuDefaultImg());
                        cartItem.setTitle(skuInfoData.getSkuTitle());
                        cartItem.setPrice(skuInfoData.getPrice());
                    },
                    executor
            );
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(
                    () -> {
                        //3、查询sku信息
                        List<String> skuSaleAttrValues = commodityFeignService.getSkuSaleAttrValues(skuId);
                        cartItem.setSkuAttr(skuSaleAttrValues);
                    },
                    executor
            );
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValuesTask).get();

            ops.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;
        }else{
            //
            CartItem cartItem = JSON.parseObject(res,CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            ops.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, String, String> ops = getCartOps();
        String res = ops.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null){
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if(CollectionUtils.isNotEmpty(tempCartItems)){
                //若临时购物车的商品不为空，则需合并
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清空临时购物车
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            cart.setItems(getCartItems(cartKey));
        }else{
            //获取临时购物车的购物项
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            cart.setItems(getCartItems(cartKey));
        }
        return cart;
    }

    private BoundHashOperations<String, String, String> getCartOps() {
        //获取用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //获取购物车 redis key
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else{
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        return stringRedisTemplate.boundHashOps(cartKey);
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(cartKey);
        if(CollectionUtils.isNotEmpty(ops.values())){
            return ops.values().stream()
                    .map(item -> JSON.parseObject(item,CartItem.class))
                    .collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey){
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check > 0);
        getCartOps().put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        getCartOps().put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        getCartOps().delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null){
            return null;
        }
        String cartKey = CART_PREFIX + userInfoTo.getUserId();

        return getCartItems(cartKey).stream()
                .filter(CartItem::getCheck)
                .peek(item -> item.setPrice(commodityFeignService.getPrice(item.getSkuId())))
                .collect(Collectors.toList());
    }
}
